const app = getApp();
const AJAX = app.$ajax,
  $wx = app.$wx;

Page({
  data: {
    swiperCurrent: 0,
    goodsParams: {
      cid: 0,
      page: 1
    },
    goodsInfo: {},
    searchVal: ''
  },

  onLoad(options){
    // 默认第一个id
    let td = this.data;
    this.getGoodsList();
  },

  onShareAppMessage(){

  },

  //搜索 
  search(e){
    let search_val = e.detail.val;
    this.getGoodsList({
      name: search_val
    }, true);
  },

  // 获取导航
  getNav(e) {
    let td = this.data, 
    ed = e.detail;

    td.goodsParams.cid = td.goodsInfo.category[ed.index].id;
    
    this.setData({
      swiperCurrent: ed.index
    }, callback => {
      this.getGoodsList(td.goodsParams);
    });
  },

  swiperChange(e) {
    let td = this.data,
    current = e.detail.current,
    goodsInfo_category = td.goodsInfo.category;

    this.setData({
      swiperCurrent: current
    });
  },

  //热门搜索
  getHotKeyword(e){
    let td = this.data,
     ed = e.currentTarget.dataset;

    this.setData({
      searchVal: ed.keyword,
      swiperCurrent: 0
    }, callback => {
      this.getGoodsList({ keyword: ed.keyword });
    });
  },

  // 获取推荐
  getRecommend(){
    let td = this.data, 
        ci = app.appData.commodityItem, 
        category = td.goodsInfo.category || {};

    for (let i = 0; i < category.length; i++) {
      if (category[i].id == ci.category.id) {
        td.goodsParams.cid = ci.category.id;

        this.setData({
          swiperCurrent: i
        }, callback => {
          this.getGoodsList(td.goodsParams);
        });
        break;
      }
    }
  },

  /**
   * 获取商品列表
   * @param category_id
   * @parma keyword
   * @param page
   * */ 
  getGoodsList(params = {}, isSearch){
    let _this = this, td = _this.data;
    params.loadType = 'bar';

    AJAX.getGoodsList(params).then(([status, res, msg]) => {
      let goodsInfo = td.goodsInfo;
      if (!goodsInfo.category) goodsInfo.category = res.categorydata;
      if (!goodsInfo.hotKeyword) goodsInfo.hotKeyword = res.hot_keyword;
        goodsInfo.list = res.goodlist;

      if (app.appData.commodityItem && JSON.stringify(app.appData.commodityItem) != '{}'){
        _this.getRecommend();
       delete app.appData.commodityItem;
       return true
      }
      
      if(isSearch){
        _this.setData({
          swiperCurrent: -1
        });
      }
      _this.setData({ goodsInfo});
    });
  }
});